<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:item:add']"
          v-if="confirm == false && refresh == false"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-circle-check"
          size="mini"
          @click="handleConfirm"
          v-hasPermi="['md:item:edit']"
          v-if="confirm == false && refresh == false"
        >确认</el-button>
        <span class="warning-message" v-if="confirm == false && refresh == false">
          确认后bom物料将无法更改！
        </span>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange" border>
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column
        label="产品物料名称"
        align="center"
        prop="itemName"
        width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产品物料编码"
        align="center"
        prop="itemCode"
        width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="物料类型"
        align="center"
        prop="itemType"
        width="100"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemType"/>
        </template>
      </el-table-column>
      <el-table-column
        label="规格"
        align="center"
        prop="specification"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
      <el-table-column
        label="单位"
        align="center"
        prop="unitOfMeasure"
        width="120"
        :show-overflow-tooltip="true" />
<!--      <el-table-column label="图纸编号" align="center" prop="drawCode" :show-overflow-tooltip="true"/>-->
      <el-table-column
        label="使用量"
        align="center"
        prop="used"
        width="100"
      />
<!--      <el-table-column label="规格" align="center" prop="model" />-->
<!--      <el-table-column label="规格单位" align="center" prop="specificationUnit"/>-->
<!--      <el-table-column label="重量" align="center" prop="weight" />-->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="100"
        v-if="confirm == false && refresh == false"
        >
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:item:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:item:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改BOM物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-row>
            <el-form-item label="产品物料编码" prop="itemCode">
              <el-input v-model="form.itemCode" readonly placeholder="请输入产品物料编码">
                <el-button slot="append" @click="handleSelectProduct" icon="el-icon-search" v-if="optType == 'add'">
                </el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
        </el-row>
        <el-row>
          <el-form-item label="产品物料名称" prop="itemName">
            <el-input v-model="form.itemName" readonly placeholder="请输入产品物料名称" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="单位" prop="unitOfMeasure">
            <el-input v-model="form.unitOfMeasure" readonly placeholder="请输入单位" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="form.specification" readonly type="textarea" placeholder="请输入规格型号" />
          </el-form-item>
        </el-row>
<!--        <el-row>-->
<!--          <el-form-item label="图纸编号" prop="drawCode" v-if="form.itemType === 'PRODUCT'">-->
<!--            <el-input v-model="form.drawCode" readonly />-->
<!--          </el-form-item>-->
<!--        </el-row>-->
        <el-row>
          <el-form-item label="使用量" prop="used">
            <el-input-number
              v-model="form.used"
              :step="1"
              :min="0.000001"
              :precision="6"
              placeholder="请输入使用量" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="BOM版本" prop="bomCode" v-if="form.itemType === 'PRODUCT'">
            <el-select v-model="form.bomCode" placeholder="请选择BOM版本" clearable @change="bomSelected">
              <el-option
                v-for="bom in bomOptions"
                :key="bom.bomCode"
                :label="bom.bomName"
                :value="bom.bomCode"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="selectedRemark" v-if="form.itemType === 'PRODUCT'">
            <el-input v-model="form.selectedRemark" type="textarea" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="创建时间" prop="selectedCreateTime" v-if="form.itemType === 'PRODUCT'">
            <el-input v-model="form.selectedCreateTime" readonly></el-input>
          </el-form-item>
        </el-row>
<!--        <el-row>-->
<!--          <el-form-item label="规格" prop="model">-->
<!--            <el-input v-model="form.model" placeholder="请输入规格" />-->
<!--          </el-form-item>-->
<!--        </el-row>-->
<!--        <el-row>-->
<!--          <el-form-item label="规格单位" prop="specificationUnit">-->
<!--            <el-select v-model="form.specificationUnit" placeholder="请选择规格单位">-->
<!--              <el-option label="米（m）" value="m"></el-option>-->
<!--              <el-option label="厘米（cm）" value="cm"></el-option>-->
<!--              <el-option label="毫米（mm）" value="mm"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-row>-->
<!--        <el-row>
          <el-form-item label="使用比例(%)" prop="proportional">
            <el-input-number v-model="form.proportional" :precision="2" :step="0.01" :max="100" :min="0" placeholder="请输入使用比例">
            </el-input-number>
          </el-form-item>
        </el-row>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem, confirmBomItem, getConfirmItem } from "@/api/mes/md/bomItem";
import { listByCode } from "@/api/mes/md/bomgl"
import ItemSelect from "@/components/itemSelect/single.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";

export default {
  name: "Item",
  dicts: ['mes_item_product'],
  components: { ItemSelect },
  props: {
    bomId: null,
    itemCode: null,
    confirm: false,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM物料表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemCode: null,
        itemName: null,
        itemType: null,
        specification: null,
        unitOfMeasure: null,
        bomId: null,
        bomCode: null,
        bomName: null,
        used: null,
        proportional: null,
        parentId: this.bomId,
      },
      // 表单参数
      form: {},
      // BOM版本下拉框数据
      bomOptions: [],
      // 开关
      refresh: false,
      // 新增/修改标识
      optType: "add",
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
        used: [
          { required: true, message: "使用量不能为空", trigger: "blur" }
        ],
        /*model: [
          { required: true, message: "规格不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => {
              const regex = /^\d+\*\d+\*\d+$/;
              if (!regex.test(value)) {
                callback(new Error('规格格式不正确，请输入格式为“数字 * 数字 * 数字”的格式！'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],*/
        /*specificationUnit: [
          { required: true, message: "规格单位不能为空", trigger: "change" }
        ],*/
        /*proportional: [
          { required: true, message: "使用比例不能为空", trigger: "blur" }
        ]*/
        bomCode: [
          {
            validator: (rule, value, callback) => {
              if (this.form.itemType === 'PRODUCT' && !value) {
                callback(new Error('产品类型物料必须选择BOM版本'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]

      },
      columnsConfig:[],
    };
  },
  created() {
    this.getList();
    this.getItemBase();
  },
  watch: {
    'bomId': function (newVal, oldVal) {
      this.queryParams.parentId = newVal;
      this.getList();
    },
  },
  methods: {
    /** 查询BOM物料列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        itemType: null,
        specification: null,
        unitOfMeasure: null,
        bomId: null,
        bomCode: null,
        bomName: null,
        used: null,
        proportional: 100,
        drawCode: null,
        parentId: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bom: null,
        model: null,
        specificationUnit: null,
        weight: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BOM物料";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM物料";
        this.optType = "update";
        this.getListByItemCode();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.parentId = this.bomId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料编号为"' + row.itemCode + '"的数据？').then(function() {
        return delItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    },
    // 物料选择开关
    handleSelectProduct(){
      this.$refs.itemSelect.showFlag = true;
    },
    // 物料选择弹出框
    onItemSelected(obj){
      if(obj !== undefined && obj !== null){
        if (obj.itemCode === this.itemCode) {
          this.$modal.msgError("不能选择自己作为物料！");
          return;
        }else {
          this.form.itemId = obj.itemId;
          this.form.itemCode = obj.itemCode;
          this.form.itemName = obj.itemName;
          this.form.itemType = obj.itemOrProduct;
          this.form.specification = obj.specification;
          this.form.unitOfMeasure = obj.unitOfMeasure;
          this.getListByItemCode()
        }
      }
    },
    // 获取BOM版本下拉框数据
    getListByItemCode() {
      listByCode(this.form.itemCode).then(response => {
        this.bomOptions = response.data;
      });
    },
    // BOM选择回调
    bomSelected(val) {
      let list = this.bomOptions
      list.forEach(e => {
        if(e.bomCode === val){
          this.form.bomId = e.bomId;
          this.form.bomName = e.bomName;
          this.form.drawCode = e.drawCode;
          this.form.selectedRemark = e.remark;
          this.form.selectedCreateTime = e.createTime;
        }
      })
    },
    // BOM物料确认
    handleConfirm() {
      this.$modal.confirm('是否确定BOM物料信息？确定后不可更改！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.itemList === null || this.itemList.length === 0) {
          this.$modal.msgError("请选择BOM物料！");
        } else {
          const data = this.bomId
          confirmBomItem(data).then(res => {
            this.getConfirmItem(data)
            this.getList();
            this.$modal.msgSuccess("确认成功");
          })
        }
      }).catch(() => {});
    },
    // 获取BOM物料确认信息
    getConfirmItem(bomId) {
      getConfirmItem(bomId).then(res => {
        this.refresh = res.rows.length > 0;
      })
    },
  }
};
</script>
<style scoped>
.warning-message {
  color: red;
  font-size: 14px;
  margin-bottom: 10px;
  margin-left: 10px;
}
</style>
